<template>
  <el-dialog
    class="add-ordinary-device-comp"
    title="设置普通设备"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :visible="visible"
    :width="$setRem(800)"
    :before-close="handleCancel">
    <el-form
      element-loading-custom-class="custom-load"
      :model="ruleForm"
      :rules="rules"
      label-suffix="："
      ref="ruleForm"
      :label-width="$setRem(140)"
      class="rule-form"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备名称" prop="deviceName" required>
            <span class="detail-text" v-if="hasDetail || hasQuit">{{ ruleForm.deviceName || '' }}</span>
            <el-input v-else type="text" clearable placeholder="请输入设备名称" v-model="ruleForm.deviceName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备型号" prop="deviceModel" required>
            <span class="detail-text" v-if="hasDetail || hasQuit">{{ ruleForm.deviceModel || '' }}</span>
            <el-input v-else type="text" placeholder="请输入设备型号" clearable v-model="ruleForm.deviceModel"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备编号" prop="deviceNo" required>
            <span class="detail-text" v-if="hasDetail || hasQuit">{{ ruleForm.deviceNo || '' }}</span>
            <el-input v-else type="text" clearable placeholder="请输入设备编号" v-model="ruleForm.deviceNo"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="进场时间" prop="marchDate" required>
            <span class="detail-text" v-if="hasDetail || hasQuit">{{ ruleForm.marchDate || '' }}</span>
            <el-date-picker
              v-else
              v-model="ruleForm.marchDate"
              format="yyyy-MM-d"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择进场时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备数量" prop="deviceNum" required>
            <span class="detail-text" v-if="hasDetail || hasQuit">
              {{ ruleForm.deviceNum }}
              <span v-if="hasQuit" class="num">剩余数量{{options.deviceNum - options.exitTotalNum || 0}}</span>
            </span>
            <el-input-number
              v-else
              :min="0"
              clearable
              :controls="false"
              placeholder="请输入数量"
              v-model="ruleForm.deviceNum">
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col v-if="(hasQuit || hasDetail) && !hasCache" :span="12">
          <el-form-item label="设备退场数量" prop="exitCurrentNum" required>
            <span class="detail-text" v-if="hasDetail">{{ options.exitTotalNum || '' }}</span>
            <el-input-number
              v-else
              :min="0"
              :max="(options.deviceNum - options.exitTotalNum) || Infinity"
              clearable
              :controls="false"
              placeholder="请输入退场数量"
              v-model="ruleForm.exitCurrentNum">
            </el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="hasQuit || (hasDetail && ruleForm.exitDate)">
        <el-col :span="12">
          <el-form-item label="退场时间" prop="exitDate" required>
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.exitDate || '' }}</span>
            <el-date-picker
              v-else
              v-model="ruleForm.exitDate"
              format="yyyy-MM-d"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择退场时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="20">
          <el-form-item label="设备附件" prop="devImagesUrl" required>
            <div class="detail-text" v-if="hasDetail || hasQuit">
              <template v-if="files">
                <el-image
                  v-if="files.hasImg"
                  class="img"
                  :src="files.url"
                  :preview-src-list="[files.url]">
                </el-image>
                <span v-else class="file-name" @click="window.open(files.url)">{{ files.name }}</span>
              </template>
            </div>
            <el-upload
              v-else
              class="upload-qualifications"
              ref="upload"
              action="#"
              :on-change="handleDownLoad"
              :on-remove="handleRemove"
              :on-preview="handleFileClick"
              :file-list="ruleForm.devImagesUrl"
              :auto-upload="false">
              <el-button slot="trigger" :loading="uploadLoading" size="small" type="primary">选取文件</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="抄送人" prop="sendUserId" required>
            <span class="detail-text" v-if="hasDetail || hasQuit">{{ ruleForm.sendUserName || '' }}</span>
            <el-select
              v-else
              placeholder="请选择抄送人"
              clearable
              filterable
              v-model="ruleForm.sendUserId">
              <el-option
                v-for="v in userList"
                :label="v.userName"
                :value="v.uuid"
                :key="v.uuid">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button
        size="medium"
        type="primary"
        :loading="btnLaoding"
        v-if="!hasDetail"
        @click="hanldeSubmit('1')">
        提 交
      </el-button>
      <el-button
        size="medium"
        type="primary"
        :loading="btnLaoding"
        v-if="hasEdit || hasAdd"
        @click="hanldeSubmit('0')">
        暂 存
      </el-button>
      <el-button size="medium" @click="handleCancel">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'add'
    },
    options: {
      type: Object,
      default: () => ({})
    },
    btnLaoding: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      ruleForm: {
        id: '',
        cacheFlag: '0',
        deviceName: '',
        deviceModel: '',
        deviceNo: '',
        marchDate: '',
        exitDate: '',
        deviceNum: 0,
        devImagesUrl: [],
        sendUserId: '',
        deviceType: '1',
        sendUserName: '',
        exitCurrentNum: 0
      },
      rules: {
        deviceName: [
          { required: true, message: '请输入设备名称' },
        ],
        deviceModel: [
          { required: true, message: '请输入设备型号' },
        ],
        deviceNo: [
          { required: true, message: '请输入设备编号' },
        ],
        deviceNum: [
          { required: true, message: '请输入设备数量' },
        ],
        exitCurrentNum: [
          { required: true, message: '请输入退场数量' },
        ],
        marchDate: [
          { required: true, message: '请选择进场时间' },
        ],
        devImagesUrl: [
          { type: 'array', required: true, message: '请上传设备附件' }
        ],
        sendUserId: [
          { required: true, message: '请选择抄送人' },
        ],
        exitDate: [
          { required: true, message: '请选择退场时间' },
        ]
      },
      // 维护人员
      maintainersList: [],
      searchList: [],
      userList: [],
      loading: false,
      uploadLoading: false,
      picLoading: false
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    userInfo() {
      return this.$store.state.userInfo;
    },
    // 当前操作人员列表
    currentList() {
      return this.searchList.length
        ? this.searchList
        : this.maintainersList;
    },
    // 附件
    files() {
      const { devImagesUrl } = this.ruleForm;
      if (Array.isArray(devImagesUrl)) {
        const files = devImagesUrl[0] || {};
        return {
          ...files,
          url: this.$checkUrl(files.url),
          hasImg: /\.jpg|\.jpeg|\.png$/.test(files.url)
        };
      }
      return null;
    },
    // 当前选择的操作人员信息
    currentItem() {
      return this.currentList.find(v => v.idNumber === this.ruleForm.operatorsId) || {};
    },
    hasDetail() {
      return this.type === 'detail';
    },
    hasAdd() {
      return this.type === 'add';
    },
    hasEdit() {
      return this.type === 'edit';
    },
    // 退场
    hasQuit() {
      return this.type === 'quit';
    },
    // 暂存
    hasCache() {
      return this.options.cacheFlag === '0';
    }
  },
  watch: {
    options: {
      deep: true,
      handler(data) {
        if (data) {
          Object.keys(this.ruleForm).forEach(key => {
            const value = data[key] || '';
            if (key === 'deviceType') {
              this.ruleForm[key] = value || '1';
              return;
            }
            if (key === 'deviceNum') {
              this.ruleForm[key] = value || 0;
              return;
            }
            if (key === 'exitCurrentNum') {
              this.ruleForm[key] = 0;
              return;
            }
            if (key === 'devImagesUrl') {
              const fileNames = value ? value.match(/([^\/])+\.\w+$/) : '';
              const fileName = Array.isArray(fileNames) ? fileNames[0] : '';
              if (value) this.ruleForm[key] = [{
                name: fileName,
                url: value
              }];
              return;
            }
            this.ruleForm[key] = value;
          });
        }
      }
    },
    visible(val) {
      if (!val) {
        this.ruleForm = {
          id: '',
          cacheFlag: '0',
          deviceName: '',
          deviceModel: '',
          deviceNo: '',
          marchDate: '',
          exitDate: '',
          deviceNum: 0,
          devImagesUrl: [],
          sendUserId: '',
          deviceType: '1',
          sendUserName: '',
          exitCurrentNum: 0
        };
        this.uploadLoading = false;
      }
    }
  },
  created() {
    this.getUserList();
  },
  methods: {
    /**
       * 获取用户列表数据
       */
    async getUserList() {
      const params = {
        pageFlag: false
      };
      const { success, data: {
        data
      }} = await this.$Model.getUserList(params);
      if (success && data) {
        this.userList = data.list || [];
      }
    },
    /**
     * 选取文件
     * @param file {File} 当前文件
     * @param fileList {FileList} 文件列表
     */
    handleDownLoad(file, fileList) {
      this.fileUpload(file.raw);
      return false;
    },
    // 上传文件
    async fileUpload(file) {
      const fm = new FormData();
      fm.append('file', file);
      this.uploadLoading = true;
      const { success, data: { data }} = await this.$Model.fileUpload(fm);
      this.uploadLoading = false;
      if (success && data) {
        this.ruleForm.devImagesUrl = [{
          name: file.name,
          url: data
        }];
      }
    },
    /**
     * 删除文件
     * @param file {File} 当前文件
     * @param fileList {FileList} 文件列表
     */
    async handleRemove(file, fileList) {
      // await this.$Model.fileDelete({ filePath: file.url });
      this.ruleForm.devImagesUrl = [];
    },
    /**
     * 点击文件列表中已上传的文件时的钩子
     * @param file {File} 当前文件
     */
    handleFileClick(file) {
      if (file.url) window.open(this.$checkUrl(file.url));
    },
    handleCancel() {
      this.$emit('cancel');
    },
    hanldeSubmit(type) {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          const {
            devImagesUrl,
            exitDate,
            exitCurrentNum,
            deviceName
          } = this.ruleForm;
          let params = {
            ...this.ruleForm,
            projectId: this.projectId,
            operatorsName: this.currentItem.name || '',
            devImagesUrl: devImagesUrl[0]
              ? devImagesUrl[0].url
              : '',
            createId: this.userInfo.uuid,
            cacheFlag: type // 0：暂存；1：发送
          };
          if (this.hasQuit) { // 退场
            params = {
              id: this.ruleForm.id,
              deviceName,
              exitDate,
              exitCurrentNum,
              deviceType: '2' // 1：入场；2：离场
            };
          } else {
            delete params.exitDate;
            delete params.exitCurrentNum;
          }
          if (!params.id) delete params.id;
          this.$emit('submit', params);
        }
      });
    },
  }
};
</script>

<style scoped lang="scss">
  @import "../../../assets/styles/table";
  @import "../../../assets/styles/dialog";

  .add-ordinary-device-comp {
    .upload-qualifications {
      .el-upload-list__item-name, .el-icon-close, .el-icon-document {
        color: #fff;
        transition: color .3s;
      }
      .el-upload-list__item:hover {
        background-color: $inputBgRbga;
        .el-upload-list__item-name, .el-icon-document, .el-icon-close {
          color: $mainColor;
        }
      }
    }
    .avatar-uploader-icon, .loading-container {
      display: block;
      font-size: 28px;
      color: #8c939d;
      width: 120px;
      height: 120px;
      line-height: 120px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      &:hover {
        border-color: $mainColor;
        color: $mainColor;
      }
    }
    .img-content {
      overflow: hidden;
      position: relative;
    }
    .el-icon-circle-close {
      position: absolute;
      cursor: pointer;
      right: 0;
      top: 0;
      font-size: 30px;
      z-index: 1;
      color: #999;
    }
    .img {
      width: 100px;
      height: 100px;
    }
    .detail-text .num {
      margin-left: 10px;
      color: $mainColor;
    }
    /deep/ .el-dialog__footer {
      margin-top: 20px;
      text-align: center;
    }
  }
</style>
